home *** CD-ROM | disk | FTP | other *** search
/ MacHack 1996 / MacHack 1996.toast / Hacks / Hacks ’92 / OK, What was that? / Application / WhatWasThat.p < prev    next >
Encoding:
Text File  |  1992-07-03  |  28.2 KB  |  845 lines  |  [TEXT/MPS ]

  1. PROGRAM Sample;
  2.  
  3. USES
  4.     MemTypes, QuickDraw, OSIntf, ToolIntf, PackIntf, Traps, Notification,
  5. {my custom stuff}
  6.     Utilities;
  7.  
  8. CONST
  9.     {MPW 3.0 will include a Traps.p interface file that includes constants for trap numbers.
  10.      These constants are from that file.}
  11.     {1.02 - since using MPW 3.0 only, we include Traps.p, so we now have trap numbers.}
  12.  
  13.     {1.01 - changed constants to begin with 'k' for consistency, except for resource IDs}
  14.     {SysEnvironsVersion is passed to SysEnvirons to tell it which version of the
  15.      SysEnvRec we understand.}
  16.     kSysEnvironsVersion        = 1;
  17.  
  18.     {OSEvent is the event number of the suspend/resume and mouse-moved events sent
  19.      by MultiFinder. Once we determine that an event is an osEvent, we look at the
  20.      high byte of the message sent to determine which kind it is. To differentiate
  21.      suspend and resume events we check the resumeMask bit.}
  22.     kOSEvent                = app4Evt;    {event used by MultiFinder}
  23.     kSuspendResumeMessage    = 1;        {high byte of suspend/resume event message}
  24.     kResumeMask                = 1;        {bit of message field for resume vs. suspend}
  25.     kNoEvents                = 0;        {no events mask}
  26.  
  27.     {1.01 - kMinHeap - This is the minimum result from the following
  28.      equation:
  29.             
  30.             ORD(GetApplLimit) - ORD(ApplicZone)
  31.             
  32.      for the application to run. It will insure that enough memory will
  33.      be around for reasonable-sized scraps, FKEYs, etc. to exist with the
  34.      application, and still give the application some 'breathing room'.
  35.      To derive this number, we ran under a MultiFinder partition that was
  36.      our requested minimum size, as given in the 'SIZE' resource.}
  37.      
  38.     kMinHeap    = 21 * 1024;
  39.     
  40.     {1.01 - kMinSpace - This is the minimum result from PurgeSpace, when called
  41.      at initialization time, for the application to run. This number acts
  42.      as a double-check to insure that there really is enough memory for the
  43.      application to run, including what has been taken up already by
  44.      pre-loaded resources, the scrap, code, and other sundry memory blocks.}
  45.      
  46.     kMinSpace    = 8 * 1024;
  47.     
  48.     {kExtremeNeg and kExtremePos are used to set up wide open rectangles and regions.}
  49.     kExtremeNeg    = -32768;
  50.     kExtremePos    = 32767 - 1;            {required for old region bug}
  51.     
  52.     {The following constants are all resource IDs, corresponding to resources in Sample.r.}
  53.     rMenuBar    = 128;                    {application's menu bar}
  54.     rAboutAlert    = 128;                    {about alert}
  55.     rUserAlert    = 129;                    {error user alert}
  56.     rNotInstalledAlert = 130;            {the extension isn’t installed}
  57.  
  58.     {The following constants are used to identify menus and their items. The menu IDs
  59.      have an "m" prefix and the item numbers within each menu have an "i" prefix.}
  60.     mApple        = 128;                    {Apple menu}
  61.     iAbout        = 1;
  62.  
  63.     mFile        = 129;                    {File menu}
  64.     iNew        = 1;
  65.     iClose        = 4;
  66.     iQuit        = 12;
  67.  
  68.     mEdit        = 130;                    {Edit menu}
  69.     iUndo        = 1;
  70.     iCut        = 3;
  71.     iCopy        = 4;
  72.     iPaste        = 5;
  73.     iClear        = 6;
  74.  
  75.     {1.01 - kDITop and kDILeft are used to locate the Disk Initialization dialogs.}
  76.     kDITop        = $0050;
  77.     kDILeft        = $0070;
  78.  
  79.  
  80. VAR
  81.     {The "g" prefix is used to emphasize that a variable is global.}
  82.  
  83.     {GMac is used to hold the result of a SysEnvirons call. This makes
  84.      it convenient for any routine to check the environment. It is
  85.      global information, anyway.}
  86.     gMac                : SysEnvRec;    {set up by Initialize}
  87.  
  88.     {GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  89.      trap is available. If it is false, we know that we must call GetNextEvent.}
  90.     gHasWaitNextEvent    : BOOLEAN;        {set up by Initialize}
  91.  
  92.     {GInBackground is maintained by our osEvent handling routines. Any part of
  93.      the program can check it to find out if it is currently in the background.}
  94.     gInBackground        : BOOLEAN;        {maintained by Initialize and DoEvent}
  95.  
  96.     gNotifyRec:            NMRec;
  97.     gHaveNotificationPosted: Boolean;
  98.  
  99. {$S Initialize}
  100. FUNCTION TrapAvailable(tNumber: INTEGER; tType: TrapType): BOOLEAN;
  101.  
  102. {Check to see if a given trap is implemented. This is only used by the
  103.  Initialize routine in this program, so we put it in the Initialize segment.
  104.  The recommended approach to see if a trap is implemented is to see if
  105.  the address of the trap routine is the same as the address of the
  106.  Unimplemented trap.}
  107. {1.02 - Needs to be called after call to SysEnvirons so that it can check
  108.  if a ToolTrap is out of range of a pre-MacII ROM.}
  109.  
  110. BEGIN
  111.     IF (tType = ToolTrap) &
  112.         (gMac.machineType > envMachUnknown) &
  113.         (gMac.machineType < envMacII) THEN BEGIN        {it's a 512KE, Plus, or SE}
  114.         tNumber := BAND(tNumber, $03FF);
  115.         IF tNumber > $01FF THEN                            {which means the tool traps}
  116.             tNumber := _Unimplemented;                    {only go to $01FF}
  117.     END;
  118.     TrapAvailable := NGetTrapAddress(tNumber, tType) <>
  119.                         GetTrapAddress(_Unimplemented);
  120. END; {TrapAvailable}
  121.  
  122.  
  123. {$S Main}
  124. FUNCTION IsDAWindow(window: WindowPtr): BOOLEAN;
  125.  
  126. {Check if a window belongs to a desk accessory.}
  127.  
  128. BEGIN
  129.     IF window = NIL THEN
  130.         IsDAWindow := FALSE
  131.     ELSE    {DA windows have negative windowKinds}
  132.         IsDAWindow := (WindowPeek(window)^.windowKind < 0);
  133. END; {IsDAWindow}
  134.  
  135.  
  136. {$S Main}
  137. FUNCTION IsAppWindow(window: WindowPtr): BOOLEAN;
  138.  
  139. {Check to see if a window belongs to the application. If the window pointer
  140.  passed was NIL, then it could not be an application window. WindowKinds
  141.  that are negative belong to the system and windowKinds less than userKind
  142.  are reserved by Apple except for windowKinds equal to dialogKind, which
  143.  mean it is a dialog.
  144.  1.02 - In order to reduce the chance of accidentally treating some window
  145.  as an AppWindow that shouldn't be, we'll only return true if the windowkind
  146.  is userKind. If you add different kinds of windows to Sample you'll need
  147.  to change how this all works.}
  148.  
  149. BEGIN
  150.     IF window = NIL THEN
  151.         IsAppWindow := FALSE
  152.     ELSE    {application windows have windowKinds = userKind (8)}
  153.         WITH WindowPeek(window)^ DO
  154.             IsAppWindow := (windowKind = userKind);
  155. END; {IsAppWindow}
  156.  
  157.  
  158. {$S Main}
  159. PROCEDURE AlertUser;
  160.  
  161. {Display an alert that tells the user an error occurred, then exit the program.
  162.  This routine is used as an ultimate bail-out for serious errors that prohibit
  163.  the continuation of the application. Errors that do not require the termination
  164.  of the application should be handled in a different manner. Error checking and
  165.  reporting has a place even in the simplest application. For simplicity, the alert
  166.  displayed here only says that an error occurred, but not what it was. There are
  167.  various methods available for being more specific.}
  168.  
  169. VAR
  170.     itemHit    : INTEGER;
  171. BEGIN
  172.     SetCursor(arrow);
  173.     itemHit := Alert(rUserAlert, NIL);
  174.     ExitToShell;
  175. END; {AlertUser}
  176.  
  177. CONST
  178. SysZone = $2A6;                 {[GLOBAL VAR] Address of system heap zone
  179.    system heap zone [pointer]}
  180. ApplZone = $2AA;                {[GLOBAL VAR] Address of application heap zone
  181.    application heap zone [pointer]}
  182.  
  183. {$S Main}
  184. PROCEDURE DoCloseWindow(window: WindowPtr);
  185. BEGIN
  186.     SetZone(SystemZone);
  187.     KillPicture(GetWindowPic(window));
  188.     SetZone(ApplicationZone);
  189.     SetWindowPic(window,NIL);
  190.     DisposeWindow(window);
  191. END; {DoCloseWindow}
  192.  
  193.  
  194.  
  195. {$S Initialize}
  196. FUNCTION Gestalt(selector: OSType;VAR response: LONGINT): OSErr;
  197. EXTERNAL;
  198. FUNCTION NewGestalt(selector: OSType;gestaltFunction: ProcPtr): OSErr;
  199. EXTERNAL;
  200. FUNCTION ReplaceGestalt(selector: OSType;gestaltFunction: ProcPtr;VAR oldGestaltFunction: ProcPtr): OSErr;
  201. EXTERNAL;
  202.  
  203. VAR    
  204.     gQueueHeader : QHdrPtr;
  205.  
  206. PROCEDURE RememberWhereMyQueueIs;
  207. VAR
  208.     err : OSErr;
  209.     itemHit    : INTEGER;
  210. BEGIN
  211. (*
  212.     Ptr(gQueueHeader) := NewPtrSys(sizeof(QHdr));
  213.  
  214.     with gQueueHeader^ do begin
  215.         qFlags:= 0;
  216.         qHead:= nil;
  217.         qTail:= nil;
  218.     end;
  219.  
  220.     err := NewGestalt('Msg!',ProcPtr(gQueueHeader));
  221. *)
  222.     err := Gestalt('Msg!',longint(gQueueHeader));
  223.     if err <> noErr then begin
  224.         SetCursor(arrow);
  225.         itemHit := Alert(rNotInstalledAlert, NIL);
  226.         ExitToShell;
  227.     end;
  228. END;
  229.  
  230.  
  231.  
  232. {$S Initialize}
  233. PROCEDURE Initialize;
  234.  
  235. {Set up the whole world, including global variables, Toolbox managers,
  236.  and menus. We also create our one application window at this time.
  237.  Since window storage is non-relocateable, how and when to allocate space
  238.  for windows is very important so that heap fragmentation does not occur.
  239.  Because Sample has only one window and it is only disposed when the application
  240.  quits, we will allocate its space here, before anything that might be a locked
  241.  relocatable object gets into the heap. This way, we can force its storage to be
  242.  in the lowest memory available in the heap. Window storage can differ widely
  243.  amongst applications depending on how many windows are created and disposed.
  244.  If a failure occurs here, we will consider that the application is in such
  245.  bad shape that we should just exit. Your error handling may differ, but
  246.  the checks should still be made.}
  247.  
  248. {1.01 - The code that used to be part of ForceEnvirons has been moved into
  249.  this module. If an error is detected, instead of merely doing an ExitToShell,
  250.  which leaves the user without much to go on, we call AlertUser, which puts
  251.  up a simple alert that just says an error occurred and then calls ExitToShell.
  252.  In the interests of keeping things simple, the alert does not state the specific
  253.  cause of the error, but a more informative alert would be appropriate for more
  254.  sophisticated applications. Since there is no other cleanup needed at this point
  255.  if an error is detected, this form of error- handling is acceptable. If more
  256.  sophisticated error recovery is needed, a signal mechanism, such as is provided
  257.  by Signals, can be used.}
  258.  
  259. VAR
  260.     menuBar            : Handle;
  261.     window            : WindowPtr;
  262.     ignoreError        : OSErr;
  263.     total, contig    : LongInt;
  264.     ignoreResult    : BOOLEAN;
  265.     event            : EventRecord;
  266.     count            : INTEGER;
  267.  
  268. BEGIN
  269.     gInBackground := FALSE;
  270.     gHaveNotificationPosted := False;
  271.  
  272.     InitGraf(@thePort);
  273.     InitFonts;
  274.     InitWindows;
  275.     InitMenus;
  276.     TEInit;
  277.     InitDialogs(NIL);
  278.     InitCursor;
  279.     
  280.     {Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  281.      if you are using it.}
  282.     {NOTE -- It is no longer necessary, and actually unhealthy, to check
  283.      PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  284.      of checking for port availability themselves.}
  285.     
  286.     {This next bit of code is necessary to allow the default button of our
  287.      alert be outlined.
  288.      1.02 - Changed to call EventAvail so that we don't lose some important
  289.      events.}
  290.      
  291.     FOR count := 1 TO 3 DO
  292.         ignoreResult := EventAvail(everyEvent, event);
  293.     
  294.     {Ignore the error returned from SysEnvirons; even if an error occurred,
  295.      the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  296.      call to SysEnvirons by calling it after initializing AppleTalk.}
  297.      
  298.     ignoreError := SysEnvirons(kSysEnvironsVersion, gMac);
  299.     
  300.     {Make sure that the machine has at least 128K ROMs. If it doesn't, exit.}
  301.     
  302.     IF gMac.machineType < 0 THEN AlertUser;
  303.     
  304.     {1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  305.      in TrapAvailable if a tool trap value is out of range.}
  306.      
  307.     gHasWaitNextEvent := TrapAvailable(_WaitNextEvent, ToolTrap);
  308.  
  309.     {1.01 - We used to make a check for memory at this point by examining ApplLimit,
  310.      ApplicZone, and StackSpace and comparing that to the minimum size we told
  311.      MultiFinder we needed. This did not work well because it assumed too much about
  312.      the relationship between what we asked MultiFinder for and what we would actually
  313.      get back, as well as how to measure it. Instead, we will use an alternate
  314.      method comprised of two steps.}
  315.      
  316.     {It is better to first check the size of the application heap against a value
  317.      that you have determined is the smallest heap the application can reasonably
  318.      work in. This number should be derived by examining the size of the heap that
  319.      is actually provided by MultiFinder when the minimum size requested is used.
  320.      The derivation of the minimum size requested from MultiFinder is described
  321.      in Sample.h. The check should be made because the preferred size can end up
  322.      being set smaller than the minimum size by the user. This extra check acts to
  323.      insure that your application is starting from a solid memory foundation.}
  324.      
  325.     IF ORD(GetApplLimit) - ORD(ApplicZone) < kMinHeap THEN AlertUser;
  326.     
  327.     {Next, make sure that enough memory is free for your application to run. It
  328.      is possible for a situation to arise where the heap may have been of required
  329.      size, but a large scrap was loaded which left too little memory. To check for
  330.      this, call PurgeSpace and compare the result with a value that you have determined
  331.      is the minimum amount of free memory your application needs at initialization.
  332.      This number can be derived several different ways. One way that is fairly
  333.      straightforward is to run the application in the minimum size configuration
  334.      as described previously. Call PurgeSpace at initialization and examine the value
  335.      returned. However, you should make sure that this result is not being modified
  336.      by the scrap's presence. You can do that by calling ZeroScrap before calling
  337.      PurgeSpace. Make sure to remove that call before shipping, though.}
  338.      
  339.     PurgeSpace(total, contig);
  340.     IF total < kMinSpace THEN AlertUser;
  341.  
  342.     {The extra benefit to waitng until after the Toolbox Managers have been initialized
  343.      before checking memory is that we can now give the user an alert to tell him what
  344.      happened. Although it is possible that the memory situation could be worsened by
  345.      displaying an alert, MultiFinder would gracefully exit the application with
  346.      an informative alert if memory became critical. Here we are acting more
  347.      in a preventative manner to avoid future disaster from low-memory problems.}
  348.  
  349.     menuBar := GetNewMBar(rMenuBar);        {read menus into menu bar}
  350.     IF menuBar = NIL THEN AlertUser;
  351.     SetMenuBar(menuBar);                    {install menus}
  352.     DisposHandle(menuBar);
  353.     AddResMenu(GetMHandle(mApple), 'DRVR');    {add DA names to Apple menu}
  354.     DrawMenuBar;
  355.  
  356.     RememberWhereMyQueueIs;
  357. END; {Initialize}
  358.  
  359.  
  360. (**************************************************************************************
  361. 1.01 - PROCEDURE DoCloseBehind(window: WindowPtr); was removed.
  362.  
  363. {1.01 - DoCloseBehind was a good idea for closing windows when quitting
  364.  and not having to worry about updating the windows, but it suffered
  365.  from a fatal flaw. If a desk accessory owned two windows, it would
  366.  close both those windows when CloseDeskAcc was called. When DoCloseBehind
  367.  got around to calling DoCloseWindow for that other window that was already
  368.  closed, things would go very poorly. Another option would be to have a
  369.  procedure, GetRearWindow, that would go through the window list and return
  370.  the last window. Instead, we decided to present the standard approach
  371.  of getting and closing FrontWindow until FrontWindow returns NIL. This
  372.  has a potential benefit in that the window whose document needs to be saved
  373.  may be visible since it is the front window, therefore decreasing the
  374.  chance of user confusion. For aesthetic reasons, the windows in the
  375.  application should be checked for updates periodically and have the
  376.  updates serviced.}
  377. **************************************************************************************)
  378.  
  379.  
  380. {$S Main}
  381. PROCEDURE Terminate;
  382.  
  383. {Clean up the application and exits. We close all of the windows so that
  384.  they can update their documents, if any.}
  385.  
  386. {1.01 - If we find out that a cancel has occurred, we won't exit to the
  387.  shell, but will return instead.}
  388.  
  389. VAR
  390.     aWindow    : WindowPtr;
  391. BEGIN
  392.     WHILE FrontWindow <> NIL DO
  393.         DoCloseWindow(FrontWindow);                {close this window}
  394.     ExitToShell;                            {exit if no cancellation}
  395. END; {Terminate}
  396.  
  397.  
  398. {$S Main}
  399. PROCEDURE PostNotification;
  400. CONST
  401.     rSmallIconID = 128;
  402. VAR
  403.     iconHandle: Handle;
  404.     err: OSErr;
  405. BEGIN
  406.     iconHandle := GetResource('SICN', rSmallIconID);
  407.     HNoPurge(iconHandle);
  408.  
  409.     gNotifyRec.qType        := ORD(nmType);       {queue type -- ORD(nmType) = 8}
  410.     gNotifyRec.nmMark        := 1;                      {item to mark in Apple menu}
  411.     gNotifyRec.nmIcon        := iconHandle;        {handle to small icon}
  412.     gNotifyRec.nmSound        := NIL;                   {handle to sound record}
  413.     gNotifyRec.nmStr        := NIL;                  {string to appear in alert}
  414.     gNotifyRec.nmResp        := NIL;                    {pointer to response routine}
  415.     gNotifyRec.nmRefCon        := 0;                       {for application use}
  416.     gHaveNotificationPosted := True;
  417.     
  418.     err := NMInstall(@gNotifyRec);
  419. END;
  420.  
  421.  
  422. {$S Main}
  423. PROCEDURE MakeNewWindow( thePicture : PicHandle );
  424. VAR
  425.     theWindow : WindowPtr;
  426.     theRect,frontWindowRect: Rect;
  427.     timeNDateString, sizeString : Str255;
  428.     dateTime : Longint;
  429. BEGIN
  430.     theRect := thePicture^^.picFrame;
  431.     if FrontWindow = NIL then
  432.         SetRect(frontWindowRect,40,2*GetMBarHeight,0,0)
  433.     else begin
  434.         frontWindowRect := FrontWindow^.portRect;
  435.         LocalToGlobal(frontWindowRect.topLeft);
  436.         LocalToGlobal(frontWindowRect.botRight);
  437.     end;
  438.     with frontWindowRect do
  439.         OffsetRect(theRect,left+20,top+20);
  440.     
  441.     NumToString(GetHandleSize(Handle(thePicture)),sizeString);
  442.     GetDateTime(dateTime);
  443.     IUTimeString(dateTime, true, timeNDateString);
  444.     sizeString := concat(timeNDateString,' ',sizeString);
  445.     theWindow := NewWindow (nil, theRect, sizeString, false, documentProc, WindowPtr(-1), true, 0);
  446.     SetWindowPic(theWindow, thePicture);
  447.     ForceOnScreen( theWindow );
  448.     ShowWindow( theWindow );
  449. END;
  450.  
  451. TYPE
  452.     ourQElem = record
  453.         qLink: QElemPtr;
  454.         qType: INTEGER;
  455.         picture: PicHandle;
  456.     end;
  457.  
  458. {$S Main}
  459.  
  460. PROCEDURE GetPicturesFromQueue;
  461. VAR
  462.     err : OSErr;
  463.     myQueue : QHdrPtr;
  464.     myQElement : ^ourQElem;
  465. BEGIN
  466.     QElemPtr(myQElement) := gQueueHeader^.qHead;
  467.     if myQElement <> NIL then begin
  468.         err := Dequeue(QElemPtr(myQElement), gQueueHeader);
  469.         if (err = noErr) THEN BEGIN
  470.             MakeNewWindow( myQElement^.picture);
  471.             if gInBackground AND (NOT gHaveNotificationPosted) THEN
  472.                     PostNotification;
  473.             SetZone(SystemZone);
  474.             DisposePtr(Ptr(myQElement));
  475.             SetZone(ApplicationZone);
  476.         END;
  477.     END;
  478. END;
  479.  
  480.  
  481. {$S Main}
  482. PROCEDURE AdjustMenus;
  483.  
  484. {Enable and disable menus based on the current state.
  485.  The user can only select enabled menu items. We set up all the menu items
  486.  before calling MenuSelect or MenuKey, since these are the only times that
  487.  a menu item can be selected. Note that MenuSelect is also the only time
  488.  the user will see menu items. This approach to deciding what enable/
  489.  disable state a menu item has the advantage of concentrating all the decision-
  490.  making in one routine, as opposed to being spread throughout the application.
  491.  Other application designs may take a different approach that may or may not be
  492.  just as valid.}
  493.  
  494. VAR
  495.     window            : WindowPtr;
  496.     menu            : MenuHandle;
  497.  
  498. BEGIN
  499.     window := FrontWindow;
  500.  
  501.     menu := GetMHandle(mFile);
  502.     IF IsDAWindow(window) THEN                {we can allow desk accessories to be closed from the menu}
  503.         EnableItem(menu, iClose)
  504.     ELSE
  505.         EnableItem(menu, iClose);
  506.  
  507.     EnableItem(menu, iNew);
  508.     
  509.     menu := GetMHandle(mEdit);
  510.     IF IsDAWindow(window) THEN BEGIN        {a desk accessory might need the edit menu}
  511.         EnableItem(menu, iUndo);
  512.         EnableItem(menu, iCut);
  513.         EnableItem(menu, iCopy);
  514.         EnableItem(menu, iPaste);
  515.         EnableItem(menu, iClear);
  516.     END ELSE BEGIN                            {but we know we do not}
  517.         DisableItem(menu, iUndo);
  518.         DisableItem(menu, iCut);
  519.         DisableItem(menu, iCopy);
  520.         DisableItem(menu, iClear);
  521.         DisableItem(menu, iPaste);
  522.     END;
  523. END; {AdjustMenus}
  524.  
  525.  
  526. {$S Main}
  527. PROCEDURE DoMenuCommand(menuResult: LONGINT);
  528.  
  529. {This is called when an item is chosen from the menu bar (after calling
  530.  MenuSelect or MenuKey). It performs the right operation for each command.
  531.  It is good to have both the result of MenuSelect and MenuKey go to
  532.  one routine like this to keep everything organized.}
  533.  
  534. VAR
  535.     menuID            : INTEGER;        {the resource ID of the selected menu}
  536.     menuItem        : INTEGER;        {the item number of the selected menu}
  537.     itemHit            : INTEGER;
  538.     daName            : Str255;
  539.     daRefNum        : INTEGER;
  540.     handledByDA        : BOOLEAN;
  541.     ignore            : BOOLEAN;
  542.  
  543. BEGIN
  544.     menuID := HiWrd(menuResult);    {use built-ins (for efficiency)...}
  545.     menuItem := LoWrd(menuResult);    {to get menu item number and menu number}
  546.     CASE menuID OF
  547.         mApple:
  548.             CASE menuItem OF
  549.                 iAbout:                {bring up alert for About}
  550.                     itemHit := Alert(rAboutAlert, NIL);
  551.                 OTHERWISE BEGIN        {all non-About items in this menu are DAs}
  552.                     GetItem(GetMHandle(mApple), menuItem, daName);
  553.                     daRefNum := OpenDeskAcc(daName);
  554.                 END;
  555.             END;
  556.         mFile:
  557.             CASE menuItem OF
  558.                 iNew:
  559.                     MakeNewWindow(GetPicture(128));
  560.                 iClose:
  561.                     if FrontWindow <> NIL then
  562.                         DoCloseWindow(FrontWindow);
  563.                 iQuit:
  564.                     Terminate;
  565.             END;
  566.         mEdit:                        {call SystemEdit for DA editing & MultiFinder}
  567.             handledByDA := SystemEdit(menuItem-1);    {since we don't do any editing}
  568.     END;
  569.     HiliteMenu(0);                    {unhighlight what MenuSelect (or MenuKey) hilited}
  570. END; {DoMenuCommand}
  571.  
  572.  
  573. {$S Main}
  574. PROCEDURE DrawWindow(window: WindowPtr);
  575.  
  576. {Draw the contents of the application window. We do some drawing in color, using
  577.  Classic QuickDraw's color capabilities. This will be black and white on old
  578.  machines, but color on color machines. At this point, the window's visRgn is
  579.  set to allow drawing only where it needs to be done.}
  580.  
  581. BEGIN
  582.     SetPort(window);
  583.  
  584. END; {DrawWindow}
  585.  
  586.  
  587. {$S Main}
  588. PROCEDURE DoContentClick(window: WindowPtr; event: EventRecord);
  589. BEGIN
  590. END; {DoContentClick}
  591.  
  592.  
  593. {$S Main}
  594. PROCEDURE DoUpdate(window: WindowPtr);
  595.  
  596. {This is called when an update event is received for a window.
  597.  It calls DrawWindow to draw the contents of an application window.
  598.  As an effeciency measure that does not have to be followed, it
  599.  calls the drawing routine only if the visRgn is non-empty. This
  600.  will handle situations where calculations for drawing or drawing
  601.  itself is very time-consuming.}
  602.  
  603. BEGIN
  604.     IF IsAppWindow(window) THEN BEGIN
  605.         BeginUpdate(window);                    {sets up the visRgn, clears updateRgn}
  606.         IF NOT EmptyRgn(window^.visRgn) THEN    {draw if updating needs to be done}
  607.             DrawWindow(window);
  608.         EndUpdate(window);                        {restores the visRgn}
  609.     END;
  610. END; {DoUpdate}
  611.  
  612.  
  613. {$S Main}
  614. PROCEDURE DoActivate(window: WindowPtr; becomingActive: BOOLEAN);
  615.  
  616. {This is called when a window is activated or deactivated.
  617.  In Sample, the Window Manager's handling of activate and
  618.  deactivate events is sufficient. Other applications may have
  619.  TextEdit records, controls, lists, etc., to activate/deactivate.}
  620.  
  621. BEGIN
  622.     IF IsAppWindow(window) THEN
  623.         IF becomingActive THEN
  624.             {do whatever you need to at activation}
  625.         ELSE
  626.             {do whatever you need to at deactivation};
  627. END; {DoActivate}
  628.  
  629.  
  630. {$S Main}
  631. PROCEDURE GetGlobalMouse(VAR mouse: Point);
  632.  
  633. {Get the global coordinates of the mouse. When you call OSEventAvail
  634.  it will return either a pending event or a null event. In either case,
  635.  the where field of the event record will contain the current position
  636.  of the mouse in global coordinates and the modifiers field will reflect
  637.  the current state of the modifiers. Another way to get the global
  638.  coordinates is to call GetMouse and LocalToGlobal, but that requires
  639.  being sure that thePort is set to a valid port.}
  640.  
  641. VAR
  642.     event    : EventRecord;
  643.     
  644. BEGIN
  645.     IF OSEventAvail(kNoEvents, event) THEN;    {we aren't interested in any events}
  646.     mouse := event.where;                    {just the mouse position}
  647. END;
  648.  
  649.  
  650. {$S Main}
  651. PROCEDURE AdjustCursor(mouse: Point; region: RgnHandle);
  652.  
  653. {Change the cursor's shape, depending on its position. This also calculates the region
  654.  where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  655.  that region, an event is generated, causing this routine to be called. This
  656.  allows us to change the region to the region the mouse is currently in. If
  657.  there is more to the event than just “the mouse moved”, we get called before the
  658.  event is processed to make sure the cursor is the right one. In any (ahem) event,
  659.  this is called again before we fall back into WNE.}
  660.  
  661.  
  662. VAR
  663.     window                : WindowPtr;
  664.     arrowRgn            : RgnHandle;
  665.     plusRgn                : RgnHandle;
  666.     globalPortRect        : Rect;
  667.     
  668.  
  669. BEGIN
  670.     window := FrontWindow;    {we only adjust the cursor when we are in front}
  671.     IF (NOT gInBackground) AND (NOT IsDAWindow(window)) THEN BEGIN
  672.         {calculate regions for different cursor shapes}
  673.         arrowRgn := NewRgn;
  674.         plusRgn := NewRgn;
  675.  
  676.         {start with a big, big rectangular region}
  677.         {1.01 - changed to kExtremeNeg and kExtremePos for consistency}
  678.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg,
  679.                             kExtremePos, kExtremePos);
  680.  
  681.         {calculate plusRgn}
  682.         IF IsAppWindow(window) THEN BEGIN
  683.             SetPort(window);            {make a global version of the portRect}
  684.             SetOrigin(-window^.portBits.bounds.left, -window^.portBits.bounds.top);
  685.             globalPortRect := window^.portRect;
  686.             RectRgn(plusRgn, globalPortRect);
  687.             SectRgn(plusRgn, window^.visRgn, plusRgn);
  688.             SetOrigin(0, 0);
  689.         END;
  690.  
  691.         {subtract other regions from arrowRgn}
  692.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  693.  
  694.         {change the cursor and the region parameter}
  695.         IF PtInRgn(mouse, plusRgn) THEN BEGIN
  696.             SetCursor(GetCursor(plusCursor)^^);
  697.             CopyRgn(plusRgn, region);
  698.         END ELSE BEGIN
  699.             SetCursor(arrow);
  700.             CopyRgn(arrowRgn, region);
  701.         END;
  702.  
  703.         {get rid of our local regions}
  704.         DisposeRgn(arrowRgn);
  705.         DisposeRgn(plusRgn);
  706.     END;
  707. END; {AdjustCursor}
  708.  
  709.  
  710. {$S Main}
  711. PROCEDURE DoEvent(event: EventRecord);
  712.  
  713. {Do the right thing for an event. Determine what kind of event it is, and call
  714.  the appropriate routines.}
  715.  
  716. VAR
  717.     part, err    : INTEGER;
  718.     window        : WindowPtr;
  719.     hit            : BOOLEAN;
  720.     key            : CHAR;
  721.     aPoint        : Point;
  722.  
  723. BEGIN
  724.     CASE event.what OF
  725.         mouseDown: BEGIN
  726.             part := FindWindow(event.where, window);
  727.             CASE part OF
  728.                 inMenuBar: BEGIN            {process the menu command}
  729.                     AdjustMenus;
  730.                     DoMenuCommand(MenuSelect(event.where));
  731.                 END;
  732.                 inSysWindow:                {let the system handle the mouseDown}
  733.                     SystemClick(event, window);
  734.                 inContent:
  735.                     IF window <> FrontWindow THEN BEGIN
  736.                         SelectWindow(window);
  737.                         {DoEvent(event);}    {use this line for "do first click"}
  738.                     END ELSE
  739.                         DoContentClick(window, event);
  740.                 inDrag:                        {pass screenBits.bounds to get all gDevices}
  741.                     DragWindow(window, event.where, screenBits.bounds);
  742.                 inGrow:;
  743.                 inGoAway:
  744.                     IF TrackGoAway(window, event.where) THEN
  745.                         DoCloseWindow(window);
  746.                 inZoomIn, inZoomOut:;
  747.             END;
  748.         END;
  749.         keyDown, autoKey: BEGIN                {check for menukey equivalents}
  750.             key := CHR(BAnd(event.message, charCodeMask));
  751.             IF BAnd(event.modifiers, cmdKey) <> 0 THEN    {Command key down}
  752.                 IF event.what = keyDown THEN BEGIN
  753.                     AdjustMenus;            {enable/disable/check menu items properly}
  754.                     DoMenuCommand(MenuKey(key));
  755.                 END;
  756.         END;                                {call DoActivate with the window and...}
  757.         activateEvt:                        {TRUE for activate, FALSE for deactivate}
  758.             DoActivate(WindowPtr(event.message), BAnd(event.modifiers, activeFlag) <> 0);
  759.         updateEvt:                          {call DoUpdate with the window to update}
  760.             BEGIN
  761.                 DoUpdate(WindowPtr(event.message));
  762.             END;
  763.         {1.01 - It is not a bad idea to at least call DIBadMount in response
  764.          to a diskEvt, so that the user can format a floppy.}
  765.         diskEvt:
  766.             IF HiWrd(event.message) <> noErr THEN BEGIN
  767.                 SetPt(aPoint, kDILeft, kDITop);
  768.                 err := DIBadMount(aPoint, event.message);
  769.             END;
  770.         kOSEvent:
  771.             CASE BAnd(BRotL(event.message, 8), $FF) OF    {high byte of message}
  772.                 kSuspendResumeMessage: BEGIN
  773.                     gInBackground := BAnd(event.message, kResumeMask) = 0;
  774.                     IF (gInBackground = false)  AND gHaveNotificationPosted THEN
  775.                      BEGIN
  776.                         err := NMRemove(@gNotifyRec);
  777.                         gHaveNotificationPosted := false;
  778.                     END;
  779.                     DoActivate(FrontWindow, NOT gInBackground);
  780.                 END;
  781.             END;
  782.         nullEvent: BEGIN
  783.             IF (gInBackground) AND NOT gHaveNotificationPosted THEN
  784.                 PostNotification;
  785.         END;
  786.     END;
  787. END; {DoEvent}
  788.  
  789.  
  790. {$S Main}
  791. PROCEDURE EventLoop;
  792.  
  793. {Get events forever, and handle them by calling DoEvent.
  794.  Get the events by calling WaitNextEvent, if it's available, otherwise
  795.  by calling GetNextEvent. Also call AdjustCursor each time through the loop.}
  796.  
  797. VAR
  798.     cursorRgn    : RgnHandle;
  799.     gotEvent    : BOOLEAN;
  800.     event        : EventRecord;
  801.     mouse        : Point;
  802.  
  803. BEGIN
  804.     cursorRgn := NewRgn;                {we’ll pass WNE an empty region the 1st time thru}
  805.     REPEAT
  806.         GetPicturesFromQueue;
  807.         
  808.         IF gHasWaitNextEvent THEN BEGIN    {put us 'asleep' forever under MultiFinder}
  809.             GetGlobalMouse(mouse);        {since we might go to sleep}
  810.             AdjustCursor(mouse, cursorRgn);
  811.             gotEvent := WaitNextEvent(everyEvent, event, 10, cursorRgn);
  812.         END ELSE BEGIN
  813.             SystemTask;                    {must be called if using GetNextEvent}
  814.             gotEvent := GetNextEvent(everyEvent, event);
  815.         END;
  816.         IF gotEvent THEN BEGIN
  817.             AdjustCursor(event.where, cursorRgn);    {make sure we have the right cursor}
  818.             DoEvent(event);
  819.         END;
  820.     UNTIL FALSE;                        {loop forever; we quit through an ExitToShell}
  821. END; {EventLoop}
  822.  
  823.  
  824. PROCEDURE _DataInit; EXTERNAL;
  825.  
  826. {This routine is part of the MPW runtime library. This external
  827.  reference to it is done so that we can unload its segment, %A5Init.}
  828.  
  829. {$S Main}
  830. BEGIN
  831.     UnloadSeg(@_DataInit);    {note that _DataInit must not be in Main!}
  832.     
  833.     {1.01 - call to ForceEnvirons removed}
  834.     {If you have stack requirements that differ from the default,
  835.      then you could use SetApplLimit to increase StackSpace at 
  836.      this point, before calling MaxApplZone.}
  837.      
  838.     MaxApplZone;            {expand the heap so code segments load at the top}
  839.  
  840.     Initialize;                {initialize the program}
  841.     UnloadSeg(@Initialize);    {note that Initialize must not be in Main!}
  842.  
  843.     EventLoop;                {call the main event loop}
  844. END.
  845.